package org.project.s.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.project.pojo.Download0;
import org.project.pojo.Message;
import org.project.pojo.Order;
import org.project.pojo.Outtime;
import org.project.service.user.ImgsService;
import org.project.service.user.Order1Service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
 * 	* @类功能:定时任务
 * 	* @作者: 钱程浩
 * 	* @时间: 2018年1月9 10:54:24
 * 	*/
 
@Component
public class TimeTask {
	@Resource
	private  Order1Service order1Service;
	
	@Resource
	private  ImgsService imgsService;
	
	
	/**
	 * 	* @方法名:自动执行发送短信(预约时间前两小时)
	 * 	* @参数:
	 * 	* @输出:
	 * 	* @备注:
	 * 	* @作者: 钱程浩
	 * 	* @时间: 2018年1月9 2:02:23
	 * 	* @修改:
	 * 	*/
	 @Scheduled(cron = "0 0/15 * * * ? ")//每隔15分钟运行一次  
	  public void domessage() {
	     
		 List<Message> list=order1Service.selectmessage();
		 Iterator<Message> it=list.iterator();
				 while(it.hasNext()){
					 Message message=it.next();
					  String messageTime0=message.getMessageTime();
					  String orderTime=message.getOrderTime();
					  String telephone=message.getTelephone();
					  Date messageTime=null;
					try {
						messageTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(messageTime0);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					 Date now=new Date();
					 if(now.after(messageTime)){
						 
							// 发短信
							SendSmsResponse response=null;
							try {
								response = SmsDemo.sendSms(telephone, orderTime, "SMS_121851034");
								order1Service.updatemessage(message);//更改消息状态 
							} catch (ClientException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							System.out.println("短信接口返回的数据----------------");
							System.out.println("Code=" + response.getCode());
							System.out.println("Message=" + response.getMessage());
							System.out.println("RequestId=" + response.getRequestId());
							System.out.println("BizId=" + response.getBizId());

						//	Thread.sleep(3000L);

							// 查明细
							if (response.getCode() != null && response.getCode().equals("OK")) {
								QuerySendDetailsResponse querySendDetailsResponse=null;
								try {
									querySendDetailsResponse = SmsDemo.querySendDetails(response
											.getBizId());
								} catch (ClientException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								System.out.println("短信明细查询接口返回数据----------------");
								System.out.println("Code=" + querySendDetailsResponse.getCode());
								System.out.println("Message="
										+ querySendDetailsResponse.getMessage());
								int i = 0;
								for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse
										.getSmsSendDetailDTOs()) {
									System.out.println("SmsSendDetailDTO[" + i + "]:");
									System.out.println("Content=" + smsSendDetailDTO.getContent());
									System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
									System.out.println("OutId=" + smsSendDetailDTO.getOutId());
									System.out
											.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
									System.out.println("ReceiveDate="
											+ smsSendDetailDTO.getReceiveDate());
									System.out
											.println("SendDate=" + smsSendDetailDTO.getSendDate());
									System.out.println("SendStatus="
											+ smsSendDetailDTO.getSendStatus());
									System.out.println("Template="
											+ smsSendDetailDTO.getTemplateCode());
								}
								System.out.println("TotalCount="
										+ querySendDetailsResponse.getTotalCount());
								System.out.println("RequestId="
										+ querySendDetailsResponse.getRequestId());
						 
						 
						 
						
						 
						 
						 
						 
						
					 }
					 
					 
					 }
					 }
				 }
		 
	  	
	 

	 
	 
	 
	 
/**
 * 	* @方法名:15天后自动删除上传的照片
 * 	* @参数:
 * 	* @输出:
 * 	* @备注:
 * 	* @作者: 钱程浩
 * 	* @时间: 2018年1月9 2:05:13
 * 	* @修改:
 * 	*/
	 @Scheduled(cron = "0 0/15 0/12 * * ?  ")//每隔12小时运行一次 
	  public void deleteurls() {
		 List<Download0>list=order1Service.selectupurls();
		 Iterator<Download0> it=list.iterator();
		 while(it.hasNext()){
			 Download0 download0=it.next();
			 String uploadTime=download0.getUploadTime();
			 Date deletetime0=null;
			 try {
				 deletetime0 = timeChaange(uploadTime);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
			Date now=new Date();
			
			 if(now.after(deletetime0)){
				  HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
				 String pic_path=getRealPath(req)+"download//";
				  String imgName=download0.getImgName();
				  
				  File file=new File(pic_path+imgName);                     
				  file.delete();                                  //删除真实图片
				  order1Service.deletebyid(download0);             //删除数据库记录
				 
				 
			 }
			 
		 }
	 }
	 
	 
	 
	 
	 
	 
	 @Scheduled(cron = "0/1 0/3 * * * ? ")//每隔3分钟运行一次 1-2 0/5 * * * ? 
	 public void doouttime(){//0 0/5 * * * ? 
		  
		   
		/*  Order order=  order1Service.selectorder1(orderid);
			 String state1=order.getState();
			
			 if(state1.equals("未支付")){
			 
			int i=imgsService.outtimeorder(orderid);*/
			
			
		 List<Outtime> list=order1Service.selectouttime();
		 Iterator<Outtime>it=list.iterator();
		 while(it.hasNext()){
			 Outtime outtime=it.next();
			 String outtime0=outtime.getOutTime();//得到数据库表里记录的过期时间
			
			 //将字符串转化为Date
			 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        Date outtime2 = null;
		       
		        	try {
						outtime2 = dateFormat.parse(outtime0);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			 
		     //得到对应的订单号   	
		     String orderid=outtime.getOrderid();
			
		     
		     Date now=new Date();
			 if(now.after(outtime2)){
				//从订单呢表里筛选此订单对应的状态 
				 Order order=  order1Service.selectorder1(orderid);
				 if(null!=order){
				 String state1=order.getState();
				
				 if(state1.equals("未支付")){
				 
				imgsService.outtimeorder(orderid);  //订单状态变成已放弃
				order1Service.deleteouttime(orderid);//在过期表中删除此条信息
				 } 
				 
				 }
			 
		       
		 }
	 
		 }
	 
	 }
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 

	
	/**
	 * 	* @方法名:计算15天之后时间
	 * 	* @参数:
	 * 	* @输出:
	 * 	* @备注:
	 * 	* @作者: 钱程浩
	 * 	* @时间: 2018年1月9 2:15:06
	 * 	* @修改:
	 * 	*/
			public static Date timeChaange (String timeStr) throws ParseException {
			
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				Date timeOfFivteen = sdf.parse(timeStr);
			
				Calendar cal2 = Calendar.getInstance();
			
				cal2.setTime(timeOfFivteen);
				cal2.add(Calendar.DAY_OF_MONTH, +15);
		
				timeOfFivteen = cal2.getTime();
		
				return timeOfFivteen;
			}
			
			
	
	 
	 
	 public static String getRealPath(HttpServletRequest request) {

			return request.getSession().getServletContext().getRealPath("/");
		}

	 
	 
	 
	 
	  public static  void send() throws ClientException{
		//设置超时时间-可自行调整
		  System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		  System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		  //初始化ascClient需要的几个参数
		  final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		  final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		  //替换成你的AK
		  final String accessKeyId = "yourAccessKeyId";//你的accessKeyId,参考本文档步骤2
		  final String accessKeySecret = "yourAccessKeySecret";//你的accessKeySecret，参考本文档步骤2
		  //初始化ascClient,暂时不支持多region（请勿修改）
		  IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
		  accessKeySecret);
		  DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		  IAcsClient acsClient = new DefaultAcsClient(profile);
		   //组装请求对象
		   SendSmsRequest request = new SendSmsRequest();
		   //使用post提交
		   request.setMethod(MethodType.POST);
		   //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		   request.setPhoneNumbers("1500000000");
		   //必填:短信签名-可在短信控制台中找到
		   request.setSignName("云通信");
		   //必填:短信模板-可在短信控制台中找到
		   request.setTemplateCode("SMS_1000000");
		   //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		   //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		   request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
		   //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
		   //request.setSmsUpExtendCode("90997");
		   //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		   request.setOutId("yourOutId");
		  //请求失败这里会抛ClientException异常
		  SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		  if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
		  //请求成功
		  }
		  
	  }
	 
	
		 
	
	 
	 
	  
		  
	    
		  
	 }
		        	  

